using B.S.Data.MES.API.Dto.InvoiceDTO;
using B.S.Data.MES.API.Dto.InvoiceDTO;
using B.S.Domain.InvoiceManagement;
using B.S.Infratrctrue;
using B.S.Requst;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.Data.MES.API.Applications.B.S.KApplications.Query.InvoiceQuery
{
   /// <summary>
   /// 获取销售发票详情查询处理程序
   /// 处理销售发票详情的查询逻辑
   /// </summary>
   public class GetSalesInvoiceDetailQueryHandler : IRequestHandler<GetSalesInvoiceDetailQuery, APIRequst<SalesInvoiceDTO>>
   {
       private readonly IBaseRepository<SalesInvoice> _salesInvoiceRepository;
       private readonly IBaseRepository<SalesInvoiceDetail> _salesInvoiceDetailRepository;

       /// <summary>
       /// 构造函数
       /// </summary>
       /// <param name="salesInvoiceRepository">销售发票仓储</param>
       /// <param name="salesInvoiceDetailRepository">销售发票明细仓储</param>
       public GetSalesInvoiceDetailQueryHandler(
           IBaseRepository<SalesInvoice> salesInvoiceRepository,
           IBaseRepository<SalesInvoiceDetail> salesInvoiceDetailRepository)
       {
           _salesInvoiceRepository = salesInvoiceRepository;
           _salesInvoiceDetailRepository = salesInvoiceDetailRepository;
       }

       /// <summary>
       /// 处理获取销售发票详情的查询
       /// </summary>
       /// <param name="request">获取销售发票详情查询请求</param>
       /// <param name="cancellationToken">取消令牌</param>
       /// <returns>处理结果，包含销售发票详情</returns>
       public async Task<APIRequst<SalesInvoiceDTO>> Handle(GetSalesInvoiceDetailQuery request, CancellationToken cancellationToken)
       {
           try
           {
               // 验证参数
               if (request.InvoiceId <= 0)
               {
                   return new APIRequst<SalesInvoiceDTO> { Code = RequstCode.失败, Msg = "发票ID不能为空" };
               }

               // 查询发票主表信息
               var salesInvoice = await _salesInvoiceRepository.GetAll()
                   .FirstOrDefaultAsync(s => s.InvoiceId == request.InvoiceId && !s.isDel, cancellationToken);

               if (salesInvoice == null)
               {
                   return new APIRequst<SalesInvoiceDTO> { Code = RequstCode.失败, Msg = "发票不存在或已被删除" };
               }

               // 查询发票明细信息
               var invoiceDetails = await _salesInvoiceDetailRepository.GetAll()
                   .Where(d => d.InvoiceId == request.InvoiceId && !d.isDel)
                   .ToListAsync(cancellationToken);

               // 构建发票DTO对象
               var salesInvoiceDTO = new SalesInvoiceDTO
               {
                   InvoiceId = salesInvoice.InvoiceId,
                   InvoiceNo = salesInvoice.InvoiceNo,
                   CustomerId = salesInvoice.CustomerId,
                   InvoiceDate = salesInvoice.InvoiceDate,
                   InvoiceStatus = salesInvoice.InvoiceStatus,
                   InvoiceType=salesInvoice.InvoiceType,
                   OrderId=salesInvoice.OrderId,
                   InvoiceStatusName = GetInvoiceStatusName(salesInvoice.InvoiceStatus),
                   InvoiceAmount = salesInvoice.InvoiceAmount,
                   TaxRate= salesInvoice.TaxRate,
                   Remarks = salesInvoice.Remarks,
                   CreateTime = salesInvoice.CreateTime,
                   CreateName = salesInvoice.CreateName,
                   UpdateTime = salesInvoice.UpdateTime,
                   UpdateName = salesInvoice.UpdateName,
                   Details = new List<SalesInvoiceDetailDTO>()
               };

               // 构建发票明细DTO列表
               foreach (var detail in invoiceDetails)
               {
                   var detailDTO = new SalesInvoiceDetailDTO
                   {
                       DetailId = detail.DetailId,
                       InvoiceId = detail.InvoiceId,
                       ProductCode = detail.ProductCode,
                       ProductName = detail.ProductName,
                       Specifications = detail.Specifications,
                       Unit = detail.Unit,
                       Quantity = detail.Quantity,
                       UnitPrice = detail.UnitPrice,
                       Amount = detail.Amount,
                       TaxRate = detail.TaxRate,
                       TaxAmount = detail.TaxAmount,
                       Remarks = detail.Remarks
                   };
                   salesInvoiceDTO.Details.Add(detailDTO);
               }

               return new APIRequst<SalesInvoiceDTO>
               {
                   Code = RequstCode.成功,
                   Data = salesInvoiceDTO,
                   Msg = "查询成功"
               };
           }
           catch (Exception ex)
           {
               // 记录异常并返回失败结果
               return new APIRequst<SalesInvoiceDTO>
               {
                   Code = RequstCode.失败,
                   Msg = $"查询失败：{ex.Message}"
               };
           }
       }

       /// <summary>
       /// 获取发票状态名称
       /// </summary>
       /// <param name="status">发票状态值</param>
       /// <returns>发票状态名称</returns>
       private string GetInvoiceStatusName(int status)
       {
           switch (status)
           {
               case 0:
                   return "待开具";
               case 1:
                   return "已开具";
               case 2:
                   return "已作废";
               case 3:
                   return "已红冲";
               default:
                   return "未知";
           }
       }
   }
}